import React, { useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  Switch,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { observer } from 'mobx-react-lite';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { RootStackParamList } from '@/route/Route';
import { useStore } from '@/route/Route';

type SettingsPageNavigationProp = StackNavigationProp<
  RootStackParamList,
  'Settings'
>;

export const SettingsPage = observer(() => {
  const navigation = useNavigation<SettingsPageNavigationProp>();
  const { authStore } = useStore();
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);
  const [autoBackup, setAutoBackup] = useState(true);
  const [dataSync, setDataSync] = useState(false);

  const handleLogout = () => {
    Alert.alert('确认退出', '确定要退出登录吗？', [
      {
        text: '取消',
        style: 'cancel',
      },
      {
        text: '确定',
        style: 'destructive',
        onPress: () => {
          authStore.logout();
        },
      },
    ]);
  };

  const handleNavigateToAbout = () => {
    navigation.navigate('About');
  };

  type SettingItem =
    | {
        id: string;
        title: string;
        subtitle: string;
        type: 'switch';
        value: boolean;
        onValueChange: (value: boolean) => void;
        icon: string;
        destructive?: boolean;
      }
    | {
        id: string;
        title: string;
        subtitle: string;
        type: 'button';
        onPress: () => void;
        icon: string;
        destructive?: boolean;
      };

  const settingsSections: Array<{
    title: string;
    items: SettingItem[];
  }> = [
    {
      title: '外观',
      items: [
        {
          id: 'theme',
          title: '深色模式',
          subtitle: '使用深色主题',
          type: 'switch',
          value: isDarkMode,
          onValueChange: setIsDarkMode,
          icon: 'moon',
        },
      ],
    },
    {
      title: '通知',
      items: [
        {
          id: 'notifications',
          title: '推送通知',
          subtitle: '接收重要消息提醒',
          type: 'switch',
          value: notificationsEnabled,
          onValueChange: setNotificationsEnabled,
          icon: 'notifications',
        },
      ],
    },
    {
      title: '数据',
      items: [
        {
          id: 'backup',
          title: '自动备份',
          subtitle: '定期备份数据到云端',
          type: 'switch',
          value: autoBackup,
          onValueChange: setAutoBackup,
          icon: 'cloud-upload',
        },
        {
          id: 'sync',
          title: '数据同步',
          subtitle: '跨设备同步数据',
          type: 'switch',
          value: dataSync,
          onValueChange: setDataSync,
          icon: 'sync',
        },
        {
          id: 'export',
          title: '导出数据',
          subtitle: '导出所有数据为文件',
          type: 'button',
          onPress: () => Alert.alert('导出', '数据导出功能开发中'),
          icon: 'download',
        },
        {
          id: 'clear',
          title: '清除缓存',
          subtitle: '释放存储空间',
          type: 'button',
          onPress: () => Alert.alert('清除缓存', '缓存清除功能开发中'),
          icon: 'trash',
        },
      ],
    },
    {
      title: '账户',
      items: [
        {
          id: 'about',
          title: '关于我们',
          subtitle: '应用信息和版本',
          type: 'button',
          onPress: handleNavigateToAbout,
          icon: 'information-circle',
        },
        {
          id: 'logout',
          title: '退出登录',
          subtitle: '安全退出当前账户',
          type: 'button',
          onPress: handleLogout,
          icon: 'log-out',
          destructive: true,
        },
      ],
    },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Ionicons name="arrow-back" size={24} color="#1e293b" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>设置</Text>
        <View style={styles.placeholder} />
      </View>

      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        {settingsSections.map((section, sectionIndex) => (
          <View key={sectionIndex} style={styles.section}>
            <Text style={styles.sectionTitle}>{section.title}</Text>
            <View style={styles.sectionContent}>
              {section.items.map((item, itemIndex) => (
                <TouchableOpacity
                  key={item.id}
                  style={[
                    styles.menuItem,
                    itemIndex === section.items.length - 1 &&
                      styles.lastMenuItem,
                  ]}
                  onPress={item.type === 'button' ? item.onPress : undefined}
                  disabled={item.type === 'switch'}
                >
                  <View style={styles.menuItemLeft}>
                    <View
                      style={[
                        styles.menuIcon,
                        item.destructive && styles.destructiveIcon,
                      ]}
                    >
                      <Ionicons
                        name={item.icon as any}
                        size={20}
                        color={item.destructive ? '#ef4444' : '#64748b'}
                      />
                    </View>
                    <View style={styles.menuText}>
                      <Text
                        style={[
                          styles.menuTitle,
                          item.destructive && styles.destructiveText,
                        ]}
                      >
                        {item.title}
                      </Text>
                      <Text style={styles.menuSubtitle}>{item.subtitle}</Text>
                    </View>
                  </View>
                  <View style={styles.menuItemRight}>
                    {item.type === 'switch' && (
                      <Switch
                        value={item.value}
                        onValueChange={item.onValueChange}
                        trackColor={{ false: '#e2e8f0', true: '#0ea5e9' }}
                        thumbColor={item.value ? '#ffffff' : '#ffffff'}
                      />
                    )}
                    {item.type === 'button' && (
                      <Ionicons
                        name="chevron-forward"
                        size={20}
                        color="#cbd5e1"
                      />
                    )}
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8fafc',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 15,
    backgroundColor: '#ffffff',
    borderBottomWidth: 1,
    borderBottomColor: '#e2e8f0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#1e293b',
  },
  placeholder: {
    width: 32,
  },
  scrollView: {
    flex: 1,
  },
  section: {
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: '#64748b',
    marginBottom: 8,
    paddingHorizontal: 20,
  },
  sectionContent: {
    backgroundColor: '#ffffff',
    marginHorizontal: 20,
    borderRadius: 12,
    overflow: 'hidden',
    elevation: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 1,
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f1f5f9',
  },
  lastMenuItem: {
    borderBottomWidth: 0,
  },
  menuItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  menuIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#f1f5f9',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 12,
  },
  destructiveIcon: {
    backgroundColor: '#fef2f2',
  },
  menuText: {
    flex: 1,
  },
  menuTitle: {
    fontSize: 16,
    color: '#1e293b',
    fontWeight: '500',
    marginBottom: 2,
  },
  menuSubtitle: {
    fontSize: 14,
    color: '#64748b',
  },
  destructiveText: {
    color: '#ef4444',
  },
  menuItemRight: {
    alignItems: 'center',
  },
});
